const mongoose = require('mongoose');

const categorySchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, '分类名称不能为空'],
    trim: true,
    minlength: [2, '分类名称至少需要2个字符'],
    maxlength: [20, '分类名称不能超过20个字符']
  },
  key: {
    type: String,
    required: [true, '分类键名不能为空'],
    trim: true,
    lowercase: true,
    unique: true,
    match: [/^[a-z0-9-]+$/, '键名只能包含小写字母、数字和连字符'],
    minlength: [2, '键名至少需要2个字符'],
    maxlength: [30, '键名不能超过30个字符']
  },
  description: {
    type: String,
    required: [true, '分类描述不能为空'],
    trim: true,
    maxlength: [200, '描述不能超过200个字符']
  },
  tags: [{
    type: String,
    trim: true
  }],
  order: {
    type: Number,
    default: 1,
    min: [1, '排序值最小为1'],
    max: [100, '排序值最大为100']
  },
  videoCount: {
    type: Number,
    default: 0
  },
  createdBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true
  },
  updatedBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  }
}, {
  timestamps: true
});

// 更新视频数量
categorySchema.methods.updateVideoCount = async function() {
  const Video = require('./video.model');
  const count = await Video.countDocuments({ category: this._id, status: 'ready' });
  this.videoCount = count;
  return this.save();
};

// 获取所有分类（按排序值排序）
categorySchema.statics.getAllCategories = async function() {
  return this.find()
    .sort({ order: 1, createdAt: -1 })
    .populate('createdBy', 'username')
    .populate('updatedBy', 'username');
};

// 根据键名查找分类
categorySchema.statics.findByKey = async function(key) {
  return this.findOne({ key: key.toLowerCase() })
    .populate('createdBy', 'username')
    .populate('updatedBy', 'username');
};

// 检查键名是否已存在
categorySchema.statics.isKeyExists = async function(key, excludeId = null) {
  const query = { key: key.toLowerCase() };
  if (excludeId) {
    query._id = { $ne: excludeId };
  }
  return this.exists(query);
};

// 导出模型
const Category = mongoose.model('Category', categorySchema);
module.exports = Category;